package com.nononsenseapps.feeder.tts.textInterface

import android.os.Build
import androidx.annotation.RequiresApi
import com.nononsenseapps.feeder.db.room.FeedItemWithFeed
import com.nononsenseapps.feeder.util.HtmlToPlainTextConverter
import fr.gaulupeau.apps.Poche.tts.TtsConverter
import fr.gaulupeau.apps.Poche.tts.bean.Article
import fr.gaulupeau.apps.Poche.tts.item.GenericItem
import fr.gaulupeau.apps.Poche.tts.item.TextItem
import fr.gaulupeau.apps.Poche.tts.source.AbstractTextInterface
import fr.gaulupeau.apps.Poche.tts.source.TtsHost

@RequiresApi(Build.VERSION_CODES.KITKAT)
class FeedItemWithFeedTextInterface(ttsConverter: TtsConverter, ttsHost: TtsHost, val item: FeedItemWithFeed): AbstractTextInterface<TtsHost>(ttsConverter, ttsHost) {

    init{
        initTextInterface(item).forEach { addItem(it) }
        restoreFromStart()
    }

     fun initTextInterface(item: FeedItemWithFeed): MutableList<GenericItem> {
         val itemList= mutableListOf<GenericItem>()
         var i=0
         val step=1000
         val strText= HtmlToPlainTextConverter().convert(item.description)
         val strLength=strText.length
         if (strLength < step )
             itemList.add(TextItem(strText, 0F, 0F, null))
         else do{
             if(i+step>=strLength)
                 itemList.add(TextItem(strText.substring(i, strLength), 0F, 0F, null))
             else
                 itemList.add(TextItem(strText.substring(i, i+step), 0F, 0F, null))
             i += step
         } while (i<strLength)
        return itemList
    }

    override fun getAlbum(): Article {
        return Article(
            item.id.toInt(),
            item.author,
            item.title,
            item.feedTitle,
            item.imageUrl
        )
    }
}
